<template>
  <div>
    <h1>购物车案例</h1>
    <div>
      <h1>商品列表</h1>
      <div class="list">
        <div class="item" v-for="(item,index) in List" :key="index">
          <img src="../assets/logo.png" />
          <div>{{item.name}}</div>
          <div class="count">
            <button @click="minusPerson(index)">-</button>
            {{item.count}}
            <button @click="addPerson(index)">+</button>
          </div>
        </div>
      </div>

      <div>总价格：{{amount}}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      List: [
        {
          name: "小米",
          price: 20,
          count: 10
        },
        {
          name: "苹果",
          price: 15,
          count: 20
        },
        {
          name: "华为",
          price: 30,
          count: 15
        }
      ]
    };
  },
  // 计算属性：因为有渲染的数据
  computed: {
    amount() {
      let res = 0;
      this.List.forEach(element => {
        // console.log(element);
        // 算出总额
        res += element.count * element.price;
      });
      // console.log(res);
      return res + "元";
    }
  },
  methods: {
    // 数量减少
    minusPerson(index) {
      // console.log(index);
      if (this.List[index].count == 1) {
        return;
      } else {
        this.List[index].count--;
      }
    },
    addPerson(index) {
      this.List[index].count++;
    }
  }
  //   watch: {yuan
  //     List: {
  //       deep: true,
  //       handler(){

  //       },
  //     },
  //   },
};
</script>

<style lang="less">
.list {
  width: 200px;
  border: 1px solid #000;
  .item {
    width: 200px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    // border: 1px solid #000;
    img {
      width: 50px;
      height: 50px;
    }
    .count {
      width: 73px;
      display: flex;
      justify-content: space-between;
      button {
        width: 25px;
        height: 25px;
      }
    }
  }
}
</style>